package com.credit.anypermission.permission

import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.credit.anypermission.interfaces.IPermissionProcessor
import com.credit.anypermission.interfaces.RequestInterceptor
import com.credit.anypermission.interfaces.RequestListener

class PermissionsHelper {

    private var activity: FragmentActivity? = null
    private var fragment: Fragment? = null

    fun setActivity(activity: FragmentActivity): PermissionsHelper {
        this.activity = activity
        return this
    }

    fun setFragment(fragment: Fragment): PermissionsHelper {
        this.fragment = fragment
        this.activity = fragment.requireActivity()
        return this
    }

    fun setContext(context: Context): PermissionsHelper {
        if(context is FragmentActivity){
            this.activity = context
        }
        return this
    }

    private var mIPermissionProcessor: IPermissionProcessor? = null
    fun initPermissions(iPermissionProcessor: IPermissionProcessor): PermissionsHelper {
        this.mIPermissionProcessor = iPermissionProcessor
        if (activity != null) {
            iPermissionProcessor.setActivity(activity!!)
        } else if (fragment != null) {
            iPermissionProcessor.setFragment(fragment!!)
        }
        return this
    }

    fun permissions(vararg permissions: String): PermissionsHelper {
        mIPermissionProcessor?.permissions(*permissions)
        return this
    }

    fun request(listener: RequestListener) {
        mIPermissionProcessor?.requestListener(listener)
    }

    fun onBeforeRequest(onBeforeRequest: RequestInterceptor<String>): PermissionsHelper {
        mIPermissionProcessor?.onBeforeRequest(onBeforeRequest)
        return this
    }

    fun onBeenDenied(onBeenDenied: RequestInterceptor<String>): PermissionsHelper {
        mIPermissionProcessor?.onBeenDenied(onBeenDenied)
        return this
    }

    fun onGoSetting(onGoSetting: RequestInterceptor<String>): PermissionsHelper {
        mIPermissionProcessor?.onGoSetting(onGoSetting)
        return this
    }
}